package com.xuzz.study.thread.lock;

import java.util.concurrent.atomic.AtomicReference;

public class ReentrantSpinLock {
    private AtomicReference<Thread> cas = new AtomicReference<>();
    private volatile int count = 0 ;
    public void lock()
    {
        Thread thread = Thread.currentThread();
        if( thread== cas.get())
        {
            count++;
            return;
        }
        while(!cas.compareAndSet(null,thread))
        {

        }
    }

    public void unlock()
    {
        Thread thread = Thread.currentThread();
        if(thread==cas.get())
        {
            if( count>0) {
                count--;
            }
            if(count==0)
            {
                cas.compareAndSet(thread,null);
            }
        }
    }
}
